package com.crm.system.controller.csd.customerManager;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.csd.customerManager.*;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerProductDetailMemberCard;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.qo.csd.customerManager.CustomerContractUpdateQO;
import com.crm.model.qo.csd.customerManager.CustomerQO;
import com.crm.model.qo.csd.customerManager.CustomerUpdateQO;
import com.crm.model.vo.csd.customerManager.*;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.system.service.csd.customerManager.ContractAndOrderService;
import com.crm.system.service.csd.customerManager.CustomerService;
import com.crm.system.service.finishOrderProductManager.FinishOrderProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yincuimei
 * @Date 2021/7/22 11:32
 * (客服部)客户管理
 */
@Slf4j
@RestController("csdCustomerController")
@RequestMapping("/csd/customerManager")
public class CustomerController {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    private CustomerService customerService;

    @Autowired
    com.crm.service.customerManager.CustomerDbService customerDbService;

    //合同&订单
    @Autowired
    private ContractAndOrderService contractAndOrderService;

    @Autowired
    private FinishOrderProductService finishOrderProductService;

    /**
     * 客户列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectCustomerList")
    public DataResponse selectCustomerList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                           @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                           @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                           @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                           CustomerQO customerQO//查询条件
    ){
        try{
            DhPageInfo<CustomerVO> customerVOList = customerService.selectCustomerVOList(customerQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerVOList);
        }catch(Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员客户列表
     * @author wangpeng
     * @return
     */
    @PostMapping("/selectCustomerMemberList")
    public DataResponse  selectCustomerMemberList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                        @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                        @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                        @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                        CustomerQO customerQO//查询条件
    ) {
        try {
            DhPageInfo<CustomerVO> customerVOList = customerService.selectCustomerMemberList(customerQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerVOList);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 非会员客户列表
     * @author wangpeng
     * @return
     */
    @PostMapping("/selectCustomerNonMemberList")
    public DataResponse  selectCustomerNonMemberList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                        @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                        @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                        @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                        CustomerQO customerQO//查询条件
    ) {
        try {
            DhPageInfo<CustomerVO> customerVOList = customerService.selectCustomerNonMemberList(customerQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerVOList);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * (客服部)客户列表--企业客户(编辑信息详情)
     * @param customerId
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectCustomerByCustomerId")
    public DataResponse selectCustomerByCustomerId(@RequestParam(value="customerId",required = false)String customerId){
        try{
            CustomerDetailVO customerDetailVO = customerService.selectCustomerDetailVO(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerDetailVO);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * (客服部)客户列表--企业客户(编辑)
     * @param customerUpdateQO
     * @author yincuimei
     * @return
     */
    @PostMapping("/updateCustomerByCustomerId")
    public DataResponse updateCustomerByCustomerId(@RequestBody CustomerUpdateQO customerUpdateQO){
        Boolean result = customerService.updateCustomerByCustomerId(customerUpdateQO);
        if(result){
            Customer esVo = customerDbService.selectCustomerById(customerUpdateQO.getCustomerId());
            syncES(esVo,customerUpdateQO.getCustomerId(),"客服部-编辑客户");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    private void syncES(Customer customer, String accountId, String msg) {

        String token = getToken(accountId,msg);

        Map<String, Object> parMap = transBean2Map(customer);
        parMap.put("authorization",token);
        parMap.put("key",accountId);
        try {
            String result = HttpUtil.post(ESurl+"/cutomer/insertOrUpdate",parMap);
            log.info(result);
        } catch (HttpException e) {
            log.info(msg+"ES同步失败");
        }
    }

    private String getToken(String accountId, String msg) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("accountId", accountId);
        try {
            return HttpUtil.post(ESurl+"/token/initToken",tokenMap);
        } catch (Exception e) {
            log.info(msg+"获取token失败");
        }
        return null;
    }

    /**
     * 对象装换map
     * @param obj
     * @return
     */
    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }

    /**
     * (客服部)客户列表--操作解锁--锁定
     * @param customerId 客户ID
     * @param type  0=解锁 2=锁定
     * @param remarks  备注
     * @param customerName 客户名称
     * @author wangpeng
     * @return
     */
    @PostMapping("/updateCustomerMembershipLevel")
    public DataResponse updateCustomerMembershipLevel(@RequestParam(value = "customerId",required = true)String customerId,
                                                      @RequestParam(value = "customerName",required = true)String customerName,
                                                      @RequestParam(value = "type",required = true)Integer type,
                                                      @RequestParam(value = "remarks",required = true)String remarks){
        try{
            if (type==0){
                Boolean result = customerService.updateCustomerMembershipLevelUnlock(customerId,remarks,customerName);
                if(result){
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
                }
                return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
            }else if(type==2){
                Boolean result = customerService.updateCustomerMembershipLevelLocking(customerId,remarks,customerName);
                if(result){
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
                }
                return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户详情-会员卡详情
     * @param customerProductDetailMemberCardId 会员卡id
     * @param memberCardNumber 会员卡号
     * @author baijian
     * @return
     */
    @PostMapping("/customerCardDetail")
    public DataResponse customerCardDetail(@RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId,
                                                   @RequestParam(value = "memberCardNumber") String memberCardNumber){
        try{
            customerService.customerCardDetail(customerProductDetailMemberCardId,memberCardNumber);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡电话答疑拨打记录
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/answerList")
    public DataResponse  answerList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                     @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                     @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                     @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                     @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
    ) {
        try {
            DhPageInfo<CustomerMemberCardDetailPhoneAnsweringRecord> list = customerService.answerList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡视频观看记录
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/videoList")
    public DataResponse  videoList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                    @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                    @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                    @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                    @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
    ) {
        try {
            DhPageInfo<CustomerMemberCardDetailVideoViewingRecord> list = customerService.videoList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡直播报名预约
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/appointmentList")
    public DataResponse  appointmentList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                   @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                   @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                   @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                   @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
                                   ) {
        try {
            DhPageInfo<CustomerMemberCardDetailLiveSignatureAppointment> list = customerService.appointmentList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡服务明细
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/customerMemberCardDetail")
    public DataResponse  appointmentList(@RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId) {
        try {
            MemberCardDetailVO memberCardDetailVO = customerService.customerMemberCardDetail(customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),memberCardDetailVO);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }



    /**
     * 会员卡刷卡记录
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/swipingList")
    public DataResponse  swipingList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                         @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                         @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                         @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                         @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
                                         ) {
        try {
            DhPageInfo<CustomerMemberCardDetailSwipingRecord> list = customerService.swipingList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡直播购买记录
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/purchaseList")
    public DataResponse  purchaseList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                     @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                     @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                     @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                     @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
                                     ) {
        try {
            DhPageInfo<CustomerMemberCardDetailLivePurchaseRecord> list = customerService.purchaseList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 会员卡点播购买记录
     * @param customerProductDetailMemberCardId 会员卡id
     * @author baijian
     * @return
     */
    @PostMapping("/demandList")
    public DataResponse  demandList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                      @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                      @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                      @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                      @RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId
                                      ) {
        try {
            DhPageInfo<CustomerMemberCardDetailDemandPurchaseRecord> list = customerService.demandList(pageIndex,pageSize,sortName,sortOrder,customerProductDetailMemberCardId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户详情-会员卡详情-修改合同的联系人姓名和联系方式
     * @param contractId 合同id
     * @author baijian
     * @return
     */
    @PostMapping("/updateContractNameAndPhone")
    public DataResponse updateContractNameAndPhone(@RequestParam(value = "customerProductDetailMemberCardId") String customerProductDetailMemberCardId,
                                                   @RequestParam(value = "contractId") String contractId,
                                                   @RequestParam(value = "contactName") String contactName,
                                                   @RequestParam(value = "contactDetails") String contactDetails,
                                                   @RequestParam(value = "startTm") String startTm,
                                                   @RequestParam(value = "endTm") String endTm){
        Boolean result = customerService.updateContractNameAndPhone(customerProductDetailMemberCardId,contractId,contactName,contactDetails,startTm,endTm);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 客户详情-会员卡详情-修改会员卡服务明细
     * @param customerMemberCardDetail 服务明细
     * @author baijian
     * @return
     */
    @PostMapping("/updateCustomerMemberCardDetail")
    public DataResponse updateCustomerMemberCardDetail(@RequestBody MemberCardDetailVO customerMemberCardDetail){
        Boolean result = customerService.updateCustomerMemberCardDetail(customerMemberCardDetail);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 合同&订单
     * (客服部)客户列表->查看-》合同&订单列表
     * 业务描述：
     *       查询未删除的合同信息及订单编号；
     *      可按审核人、当前状态、合同开始日期(前端列是有效起止)排序
     *      默认按合同开始日期排序(倒序)
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectContractAndOrderVOList")
    public DataResponse selectContractAndOrderVOList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                           @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                           @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                           @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc
                                           @RequestParam(value="customerId",required = true) String customerId,//客户ID
                                           @RequestParam(value="queryType",required = false) String queryType//查询类型-合同or订单
    ){
        DhPageInfo<ContractAndOrderVO> dhPageInfo = contractAndOrderService.selectContractAndOrderVOList(customerId,queryType,pageIndex,pageSize,sortName,sortOrder);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),dhPageInfo);
    }

    /**
     *(客服部)合同&订单列表-》合同查看-》合同编辑详情
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectContractDetailVOById")
    public DataResponse selectContractDetailVOById(@RequestParam(value = "contractId", required = true) String contractId){
        ContractDetailVO contractDetailVO = contractAndOrderService.selectContractDetailVOById(contractId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractDetailVO);
    }

    /**
     *(客服部)合同&订单列表-》查看-》编辑合同
     * @param customerContractUpdateQO
     * @author yincuimei
     * @return
     */
    @PostMapping("/updateCustomerContract")
    public DataResponse updateCustomerContract(@RequestBody CustomerContractUpdateQO customerContractUpdateQO){
        Boolean result = contractAndOrderService.updateCustomerContract(customerContractUpdateQO);
        ESUtil.syncConctract(customerContractUpdateQO.getContractId(),ESurl);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * (客服部)客户列表--客户详情-会员卡信息-作废会员卡
     * @param customerProductDetailMemberCard 会员卡
     * @author baijian
     * @return
     */
    @PostMapping("/updateCustomerProductDetailMemberCard")
    public DataResponse updateCustomerProductDetailMemberCard(@RequestBody CustomerProductDetailMemberCard customerProductDetailMemberCard){
        Boolean result = customerService.updateCustomerProductDetailMemberCard(customerProductDetailMemberCard);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 通过finishId查询finsh产品数据
     * @param finishOrderProductId 订单完成产品id
     * @author baijian
     * @return
     */
    @PostMapping("/selectFinishOrderProductById")
    public DataResponse selectFinishOrderProductById(@RequestParam(value="finishOrderProductId",required = false) String finishOrderProductId
    ){
        FinishOrderProduct finishOrderProduct = finishOrderProductService.selectFinishOrderProductById(finishOrderProductId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),finishOrderProduct);
    }

    /**
     * (客服部)客户列表--客户详情-产品信息-修改产品
     * @author baijian
     * @return
     */
    @PostMapping("/updateFinishOrderProduct")
    public DataResponse updateFinishOrderProduct(FinishOrderProduct finishOrderProduct,
                                                 @RequestParam(value = "logRemark") String logRemark
    ){
        Boolean result = customerService.updateFinishOrderProduct(finishOrderProduct,logRemark);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    @PostMapping("/addCustomerContract")
    public DataResponse addCustomerContract(String contractAnnexId,String customerId,String customerName,String contractStartDate,String contractEndDate,String contractReviewNotes)throws ParseException {
        try {
            Map map = contractAndOrderService.addCustomerContract(contractAnnexId,customerId,customerName,contractStartDate,contractEndDate,contractReviewNotes);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),map);
        }catch (Exception e){
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }

    }


}
